package main

import (
	"fmt"
	"net"
	"sync"
)

type Server struct {
	Ip   string
	Port int

	//在线用户的列表
	OnlineMap map[string]*User
	mapLock   sync.RWMutex

	//消息广播的channel
	Message chan string
}

// 创建一个Server 的接口
func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
	return server
}

//	监听message广播消息channel的goroutine，一旦有消息就发送给所有的在线user
func (this *Server) ListenMessager() {
	for {
		msg := <-this.Message
		//将msg 发送给全部在线的User
		this.mapLock.Lock()
		for _, cli := range this.OnlineMap {
			cli.C <- msg
		}
		this.mapLock.Unlock()
	}

}

//广播消息的方法
func (this *Server) BroadCast(user *User, msg string) {
	sendMsg := "[" + user.Addr + "]" + user.Name + ":" + msg

	this.Message <- sendMsg
}

func (this *Server) Handle(conn net.Conn) {
	// 当前链接的业务
	//fmt.Println("链接建立成功")

	user := NewUser(conn, this)
	// 用户上线将用户加入到onlineMap中
	user.Online()

	//接受客户端发送的消息
	go func() {
		buf := make([]byte, 4096)
		for {
			n, err := conn.Read(buf)
			if n == 0 {
				//this.BroadCast(user, "下线")
				user.Offline()
				return
			}
			if err != nil {
				fmt.Println("Conn Read error: ", err)
				return
			}

			//提取用户的消息 (去除'\n')
			msg := string(buf[:n-1])

			// 将得到的消息进行广播
			//this.BroadCast(user, msg)
			user.DoMessage(msg)
		}
	}()

	//当前handler阻塞
	select {}
}

// start server 的接口
func (this *Server) Start() {
	// listen
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port))
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer listener.Close()

	//启动监听message的goroutine
	go this.ListenMessager()

	for {
		// accept
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("listener accept error:", err)
			continue
		}

		go this.Handle(conn)
	}
	// do handlerd

	//close listen
}
